#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define SIZE 1024

char buf[SIZE+1];

int main(int argc,char* argv[])
{
    if(argc == 1)
    {
        printf("LZIP: file1 file2 ...\n");
        return 1;
    }
    FILE* fp2 = fopen("./t","ab");
    for(int i = 1; i < argc; ++i)
    {
        FILE* fp = fopen(argv[i],"r");
        if(fp == NULL)
        {
            perror("LZIP");
            fclose(fp2);
            exit(1);
        }
        while(fgets(buf,SIZE,fp) != NULL)
        {
            char output[SIZE+1];
            int start = 0, end = strlen(buf);
            int i = 0;
            while(start < end)
            {
                if(buf[start] != buf[start+1])
                {
                    output[i++] = buf[start++];
                    continue;
                }
                else
                {
                    //先清空前面不连续的字符数组存储的数据
                    if(i != 0)
                    {
                        fwrite(output,sizeof(char),i,fp2);
                        i = 0;
                    }
                    int count = 2;
                    for(int j = start+2; j < end; ++j)
                    {
                        if(buf[j] == buf[start])
                            ++count;
                        else
                            break;
                    }
                    fwrite(&count,sizeof(int),1,fp2);
                    fwrite(buf+start,sizeof(char),1,fp2);
                    start += count;
                }
            }
            if(i != 0)
                fwrite(output,sizeof(char),i,fp2);
            // output[0] = '\0';
            // fwrite(output,1,1,fp2);
        }
        fclose(fp);
    }
    fclose(fp2);
    return 0;
}